package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.CollectionService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.constants.UserConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.utils.thread.WeMediaThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class CollectionServiceImpl implements CollectionService {
    @Autowired
    private CacheService cacheService;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 文章收藏
     *
     * @param dto
     */
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        //1.参数校验
        if(dto == null || dto.getEntryId() == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.COLLECTION);
        updateArticleMess.setArticleId(dto.getEntryId());


        //2.业务处理
        //2.1获取userId
        Integer userId = WeMediaThreadLocalUtil.get();
        if(userId == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        //2.2更新数据到redis
        //验证数据是否已经存在
        Object data = cacheService.hGet(UserConstants.COLLECTION_BEHAVIOR + dto.getEntryId().toString(), userId.toString());
        if(dto.getOperation() == 0){//收藏
            if(data != null)
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"无法重复收藏");
            //保存数据
            cacheService.hPut(UserConstants.COLLECTION_BEHAVIOR + dto.getEntryId().toString(),userId.toString(), String.valueOf(dto));
            updateArticleMess.setAdd(1);
        }else {//取消收藏
            if(data == null)
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"您并未收藏");
            //删除数据
            cacheService.hDelete(UserConstants.COLLECTION_BEHAVIOR + dto.getEntryId().toString(),userId.toString());
            updateArticleMess.setAdd(-1);
        }

        //2.3更新数据到数据库
        Map<String,Object> map = new HashMap<>();
        map.put("articleId",dto.getEntryId());
        map.put("type","collection");    //更新article表的对应属性字段
        map.put("operation",dto.getOperation());

//        kafkaTemplate.send("article_topic", JSON.toJSONString(map));
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(updateArticleMess));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
